<template>
  <CollapsibleSection
    title="既往史"
    :is-expanded="isExpanded"
    @toggle="$emit('toggle')"
  >

  <!-- 既往史 -->
  <div class="form-container">
    <p class="tip">系统性回顾清单，确保全面无遗漏</p>

    <form>
      <!-- 1. 慢性疾病史 -->
      <div class="section">
        <div class="section-title">
          <span class="section-number">1</span>
          <span>慢性疾病史</span>
        </div>

        <!-- 心血管系统 -->
        <div class="subsection">
          <div class="subsection-title">心血管系统</div>
          <div class="checkbox-group">
            <div class="checkbox-item" :class="{ 'is-checked': form.chronic.cardiovascular.items.includes('高血压') }" @click="toggleCheckbox(form.chronic.cardiovascular.items, '高血压')">
              <input type="checkbox" :checked="form.chronic.cardiovascular.items.includes('高血压')" @change.stop /> 高血压
            </div>
            <div class="checkbox-item" :class="{ 'is-checked': form.chronic.cardiovascular.items.includes('冠心病') }" @click="toggleCheckbox(form.chronic.cardiovascular.items, '冠心病')">
              <input type="checkbox" :checked="form.chronic.cardiovascular.items.includes('冠心病')" @change.stop /> 冠心病
            </div>
            <div class="checkbox-item" :class="{ 'is-checked': form.chronic.cardiovascular.items.includes('心力衰竭') }" @click="toggleCheckbox(form.chronic.cardiovascular.items, '心力衰竭')">
              <input type="checkbox" :checked="form.chronic.cardiovascular.items.includes('心力衰竭')" @change.stop /> 心力衰竭
            </div>
            <div class="checkbox-item" :class="{ 'is-checked': form.chronic.cardiovascular.items.includes('风心病') }" @click="toggleCheckbox(form.chronic.cardiovascular.items, '风心病')">
              <input type="checkbox" :checked="form.chronic.cardiovascular.items.includes('风心病')" @change.stop /> 风心病
            </div>
            <div class="checkbox-item" :class="{ 'is-checked': form.chronic.cardiovascular.items.includes('其他') }" @click="toggleCheckbox(form.chronic.cardiovascular.items, '其他')">
              <input type="checkbox" :checked="form.chronic.cardiovascular.items.includes('其他')" @change.stop />
              <span class="checkbox-label">其他</span>
              <input v-if="form.chronic.cardiovascular.items.includes('其他')" class="inline-input" type="text" placeholder="具体疾病" v-model="form.chronic.cardiovascular.other" @click.stop />
            </div>
          </div>
          <div v-if="form.chronic.cardiovascular.items.length > 0" class="details-section">
            <div class="form-group">
              <label for="cardiovascular-diagnosis">诊断详情</label>
              <textarea 
                id="cardiovascular-diagnosis" 
                class="form-input"
                rows="3" 
                :value="form.chronic.cardiovascular.details"
                @input="(e: any) => handleTextareaInput('chronic.cardiovascular.details', e)"
                placeholder="记录：病名、诊断时间、控制情况、用药"
              ></textarea>
            </div>
          </div>
        </div>

        <!-- 内分泌系统 -->
        <div class="subsection">
          <div class="subsection-title">内分泌系统</div>
          <div class="checkbox-group">
            <div class="checkbox-item" :class="{ 'is-checked': form.chronic.endocrine.items.includes('糖尿病') }" @click="toggleCheckbox(form.chronic.endocrine.items, '糖尿病')">
              <input type="checkbox" :checked="form.chronic.endocrine.items.includes('糖尿病')" @change.stop /> 糖尿病
            </div>
            <div class="checkbox-item" :class="{ 'is-checked': form.chronic.endocrine.items.includes('甲状腺疾病') }" @click="toggleCheckbox(form.chronic.endocrine.items, '甲状腺疾病')">
              <input type="checkbox" :checked="form.chronic.endocrine.items.includes('甲状腺疾病')" @change.stop /> 甲状腺疾病
            </div>
            <div class="checkbox-item" :class="{ 'is-checked': form.chronic.endocrine.items.includes('肾上腺疾病') }" @click="toggleCheckbox(form.chronic.endocrine.items, '肾上腺疾病')">
              <input type="checkbox" :checked="form.chronic.endocrine.items.includes('肾上腺疾病')" @change.stop /> 肾上腺疾病
            </div>
            <div class="checkbox-item" :class="{ 'is-checked': form.chronic.endocrine.items.includes('其他') }" @click="toggleCheckbox(form.chronic.endocrine.items, '其他')">
              <input type="checkbox" :checked="form.chronic.endocrine.items.includes('其他')" @change.stop />
              <span class="checkbox-label">其他</span>
              <input v-if="form.chronic.endocrine.items.includes('其他')" class="inline-input" type="text" placeholder="具体疾病" v-model="form.chronic.endocrine.other" @click.stop />
            </div>
          </div>
          <div v-if="form.chronic.endocrine.items.length > 0" class="details-section">
            <div class="form-group">
              <label for="endocrine-diagnosis">诊断详情</label>
              <textarea 
                id="endocrine-diagnosis" 
                class="form-input"
                rows="3" 
                :value="form.chronic.endocrine.details"
                @input="(e: any) => handleTextareaInput('chronic.endocrine.details', e)"
                placeholder="记录：病名、诊断时间、控制情况、用药/胰岛素"
              ></textarea>
            </div>
          </div>
        </div>

        <!-- 呼吸系统 -->
        <div class="subsection">
          <div class="subsection-title">呼吸系统</div>
          <div class="checkbox-group">
            <div class="checkbox-item" :class="{ 'is-checked': form.chronic.respiratory.items.includes('哮喘') }" @click="toggleCheckbox(form.chronic.respiratory.items, '哮喘')">
              <input type="checkbox" :checked="form.chronic.respiratory.items.includes('哮喘')" @change.stop /> 哮喘
            </div>
            <div class="checkbox-item" :class="{ 'is-checked': form.chronic.respiratory.items.includes('COPD') }" @click="toggleCheckbox(form.chronic.respiratory.items, 'COPD')">
              <input type="checkbox" :checked="form.chronic.respiratory.items.includes('COPD')" @change.stop /> COPD
            </div>
            <div class="checkbox-item" :class="{ 'is-checked': form.chronic.respiratory.items.includes('肺结核') }" @click="toggleCheckbox(form.chronic.respiratory.items, '肺结核')">
              <input type="checkbox" :checked="form.chronic.respiratory.items.includes('肺结核')" @change.stop /> 肺结核
            </div>
            <div class="checkbox-item" :class="{ 'is-checked': form.chronic.respiratory.items.includes('支气管扩张') }" @click="toggleCheckbox(form.chronic.respiratory.items, '支气管扩张')">
              <input type="checkbox" :checked="form.chronic.respiratory.items.includes('支气管扩张')" @change.stop /> 支气管扩张
            </div>
            <div class="checkbox-item" :class="{ 'is-checked': form.chronic.respiratory.items.includes('其他') }" @click="toggleCheckbox(form.chronic.respiratory.items, '其他')">
              <input type="checkbox" :checked="form.chronic.respiratory.items.includes('其他')" @change.stop />
              <span class="checkbox-label">其他</span>
              <input v-if="form.chronic.respiratory.items.includes('其他')" class="inline-input" type="text" placeholder="具体疾病" v-model="form.chronic.respiratory.other" @click.stop />
            </div>
          </div>
          <div v-if="form.chronic.respiratory.items.length > 0" class="details-section">
            <div class="form-group">
              <label for="respiratory-diagnosis">诊断详情</label>
              <textarea 
                id="respiratory-diagnosis" 
                class="form-input"
                rows="3" 
                :value="form.chronic.respiratory.details"
                @input="(e: any) => handleTextareaInput('chronic.respiratory.details', e)"
                placeholder="记录：病名、病程、稳定期、急性发作频率、用药"
              ></textarea>
            </div>
          </div>
        </div>

        <!-- 消化系统 -->
        <div class="subsection">
          <div class="subsection-title">消化系统</div>
          <div class="checkbox-group">
            <div class="checkbox-item" :class="{ 'is-checked': form.chronic.digestive.items.includes('肝炎') }" @click="toggleCheckbox(form.chronic.digestive.items, '肝炎')">
              <input type="checkbox" :checked="form.chronic.digestive.items.includes('肝炎')" @change.stop /> 肝炎
            </div>
            <div class="checkbox-item" :class="{ 'is-checked': form.chronic.digestive.items.includes('肝硬化') }" @click="toggleCheckbox(form.chronic.digestive.items, '肝硬化')">
              <input type="checkbox" :checked="form.chronic.digestive.items.includes('肝硬化')" @change.stop /> 肝硬化
            </div>
            <div class="checkbox-item" :class="{ 'is-checked': form.chronic.digestive.items.includes('消化性溃疡') }" @click="toggleCheckbox(form.chronic.digestive.items, '消化性溃疡')">
              <input type="checkbox" :checked="form.chronic.digestive.items.includes('消化性溃疡')" @change.stop /> 消化性溃疡
            </div>
            <div class="checkbox-item" :class="{ 'is-checked': form.chronic.digestive.items.includes('炎症性肠病') }" @click="toggleCheckbox(form.chronic.digestive.items, '炎症性肠病')">
              <input type="checkbox" :checked="form.chronic.digestive.items.includes('炎症性肠病')" @change.stop /> 炎症性肠病
            </div>
            <div class="checkbox-item" :class="{ 'is-checked': form.chronic.digestive.items.includes('其他') }" @click="toggleCheckbox(form.chronic.digestive.items, '其他')">
              <input type="checkbox" :checked="form.chronic.digestive.items.includes('其他')" @change.stop />
              <span class="checkbox-label">其他</span>
              <input v-if="form.chronic.digestive.items.includes('其他')" class="inline-input" type="text" placeholder="具体疾病" v-model="form.chronic.digestive.other" @click.stop />
            </div>
          </div>
          <div v-if="form.chronic.digestive.items.length > 0" class="details-section">
            <div class="form-group">
              <label for="digestive-diagnosis">诊断详情</label>
              <textarea 
                id="digestive-diagnosis" 
                class="form-input"
                rows="3" 
                :value="form.chronic.digestive.details"
                @input="(e: any) => handleTextareaInput('chronic.digestive.details', e)"
                placeholder="记录：病名、病程、治疗情况"
              ></textarea>
            </div>
          </div>
        </div>

        <!-- 其他系统 -->
        <div class="subsection">
          <div class="subsection-title">其他系统</div>
          <div class="checkbox-group">
            <div class="checkbox-item" :class="{ 'is-checked': form.chronic.otherSystems.items.includes('肾脏疾病') }" @click="toggleCheckbox(form.chronic.otherSystems.items, '肾脏疾病')">
              <input type="checkbox" :checked="form.chronic.otherSystems.items.includes('肾脏疾病')" @change.stop /> 肾脏疾病
            </div>
            <div class="checkbox-item" :class="{ 'is-checked': form.chronic.otherSystems.items.includes('神经系统疾病') }" @click="toggleCheckbox(form.chronic.otherSystems.items, '神经系统疾病')">
              <input type="checkbox" :checked="form.chronic.otherSystems.items.includes('神经系统疾病')" @change.stop /> 神经系统疾病
            </div>
            <div class="checkbox-item" :class="{ 'is-checked': form.chronic.otherSystems.items.includes('血液系统疾病') }" @click="toggleCheckbox(form.chronic.otherSystems.items, '血液系统疾病')">
              <input type="checkbox" :checked="form.chronic.otherSystems.items.includes('血液系统疾病')" @change.stop /> 血液系统疾病
            </div>
            <div class="checkbox-item" :class="{ 'is-checked': form.chronic.otherSystems.items.includes('自身免疫病') }" @click="toggleCheckbox(form.chronic.otherSystems.items, '自身免疫病')">
              <input type="checkbox" :checked="form.chronic.otherSystems.items.includes('自身免疫病')" @change.stop /> 自身免疫病
            </div>
            <div class="checkbox-item" :class="{ 'is-checked': form.chronic.otherSystems.items.includes('精神疾病') }" @click="toggleCheckbox(form.chronic.otherSystems.items, '精神疾病')">
              <input type="checkbox" :checked="form.chronic.otherSystems.items.includes('精神疾病')" @change.stop /> 精神疾病
            </div>
            <div class="checkbox-item" :class="{ 'is-checked': form.chronic.otherSystems.items.includes('恶性肿瘤') }" @click="toggleCheckbox(form.chronic.otherSystems.items, '恶性肿瘤')">
              <input type="checkbox" :checked="form.chronic.otherSystems.items.includes('恶性肿瘤')" @change.stop /> 恶性肿瘤
            </div>
            <div class="checkbox-item" :class="{ 'is-checked': form.chronic.otherSystems.items.includes('其他') }" @click="toggleCheckbox(form.chronic.otherSystems.items, '其他')">
              <input type="checkbox" :checked="form.chronic.otherSystems.items.includes('其他')" @change.stop />
              <span class="checkbox-label">其他</span>
              <input v-if="form.chronic.otherSystems.items.includes('其他')" class="inline-input" type="text" placeholder="具体疾病" v-model="form.chronic.otherSystems.other" @click.stop />
            </div>
          </div>
          <div v-if="form.chronic.otherSystems.items.length > 0" class="details-section">
            <div class="form-group">
              <label for="other-systems-diagnosis">诊断详情</label>
              <textarea 
                id="other-systems-diagnosis" 
                class="form-input"
                rows="3" 
                :value="form.chronic.otherSystems.details"
                @input="(e: any) => handleTextareaInput('chronic.otherSystems.details', e)"
                placeholder="记录：病名、诊断时间、治疗史、目前状态"
              ></textarea>
            </div>
          </div>
        </div>

        <div class="no-history">
          <div class="checkbox-item" :class="{ 'is-checked': form.noChronicDisease }" @click="form.noChronicDisease = !form.noChronicDisease; onNoChronicChange()">
            <input type="checkbox" :checked="form.noChronicDisease" @change.stop /> 无慢性疾病史
          </div>
        </div>
      </div>

      <!-- 2. 外科情况 -->
      <div class="section">
        <div class="section-title">
          <span class="section-number">2</span>
          <span>外科情况</span>
        </div>

        <!-- 手术史 -->
        <div class="subsection">
          <div class="subsection-title">手术史</div>
          <div id="surgery-container">
            <div class="surgery-item" v-for="(s, sIdx) in form.surgeries" :key="s.id">
              <button v-if="form.surgeries.length > 1" type="button" class="remove-btn" @click="removeSurgery(sIdx)">删除</button>
              <div class="form-group">
                <label :for="`surgery-name-${sIdx}`">手术名称</label>
                <nut-input :id="`surgery-name-${sIdx}`" v-model:model-value="s.name" placeholder="如：阑尾切除术" />
              </div>
              <div class="form-group">
                <label :for="`surgery-date-${sIdx}`">手术日期</label>
                <picker mode="date" :value="form.surgeries[sIdx].date || getTodayString()" @change="(e) => onSurgeryPickerChange(e, sIdx)">
                  <div class="date-display" :id="`surgery-date-${sIdx}`">
                    {{ form.surgeries[sIdx].date || '请选择日期' }}
                  </div>
                </picker>
              </div>
              <div class="form-group">
                <label :for="`surgery-reason-${sIdx}`">手术原因</label>
                <nut-input :id="`surgery-reason-${sIdx}`" v-model:model-value="s.reason" placeholder="如：急性阑尾炎" />
              </div>
              <div class="form-group">
                <label :for="`surgery-hospital-${sIdx}`">施术医院</label>
                <nut-input :id="`surgery-hospital-${sIdx}`" v-model:model-value="s.hospital" placeholder="请输入医院" />
              </div>
              <div class="form-group">
                <label :for="`surgery-complications-${sIdx}`">有无并发症</label>
                <textarea 
                  :id="`surgery-complications-${sIdx}`" 
                  class="form-input"
                  rows="2" 
                  :value="s.complications"
                  @input="(e: any) => handleTextareaInput(`surgeries.complications-${sIdx}`, e)"
                  placeholder="如有，请描述"
                ></textarea>
              </div>
            </div>
          </div>
          <nut-button block type="primary" @click="addSurgery">添加手术记录</nut-button>
        </div>

        <!-- 外伤史 -->
        <div class="subsection">
          <div class="subsection-title">外伤史</div>
          <div id="trauma-container">
            <div class="disease-item" v-for="(t, tIdx) in form.traumas" :key="t.id">
              <nut-button v-if="form.traumas.length > 1" block type="danger" plain @click="removeTrauma(tIdx)">删除</nut-button>
              <div class="form-group">
                <label :for="`trauma-type-${tIdx}`">外伤类型</label>
                <nut-input :id="`trauma-type-${tIdx}`" v-model:model-value="t.type" placeholder="如：左下肢骨折" />
              </div>
              <div class="form-group">
                <label :for="`trauma-date-${tIdx}`">发生时间</label>
                <picker mode="date" :value="form.traumas[tIdx].date || getTodayString()" @change="(e) => onTraumaPickerChange(e, tIdx)">
                  <div class="date-display" :id="`trauma-date-${tIdx}`">
                    {{ form.traumas[tIdx].date || '请选择日期' }}
                  </div>
                </picker>
              </div>
              <div class="form-group">
                <label :for="`trauma-treatment-${tIdx}`">处理方式</label>
                <nut-input :id="`trauma-treatment-${tIdx}`" v-model:model-value="t.treatment" placeholder="如：石膏固定" />
              </div>
              <div class="form-group">
                <label :for="`trauma-sequelae-${tIdx}`">后遗症</label>
                <nut-input :id="`trauma-sequelae-${tIdx}`" v-model:model-value="t.sequelae" placeholder="如：跛行" />
              </div>
            </div>
          </div>
          <nut-button block type="primary" @click="addTrauma">添加外伤记录</nut-button>
        </div>

        <div class="no-history">
          <div class="checkbox-item" :class="{ 'is-checked': form.noSurgicalHistory }" @click="form.noSurgicalHistory = !form.noSurgicalHistory; onNoSurgicalChange()">
            <input type="checkbox" :checked="form.noSurgicalHistory" @change.stop /> 无外科情况
          </div>
        </div>
      </div>

      <!-- 3. 输血史 -->
      <div class="section">
        <div class="section-title">
          <span class="section-number">3</span>
          <span>输血史</span>
        </div>

        <div id="transfusion-container">
          <div class="disease-item" v-for="(tr, trIdx) in form.transfusions" :key="tr.id">
            <button v-if="form.transfusions.length > 1" type="button" class="remove-btn" @click="removeTransfusion(trIdx)">删除</button>
            <div class="form-group">
              <label :for="`transfusion-reason-${trIdx}`">输血原因</label>
              <nut-input :id="`transfusion-reason-${trIdx}`" v-model:model-value="tr.reason" placeholder="如：手术中失血" />
            </div>
            <div class="form-group">
              <label :for="`transfusion-date-${trIdx}`">输血时间</label>
              <picker mode="date" :value="form.transfusions[trIdx].date || getTodayString()" @change="(e) => onTransfusionPickerChange(e, trIdx)">
                <div class="date-display" :id="`transfusion-date-${trIdx}`">
                  {{ form.transfusions[trIdx].date || '请选择日期' }}
                </div>
              </picker>
            </div>
            <div class="form-group">
              <label :for="`blood-type-${trIdx}`">血型</label>
              <nut-input :id="`blood-type-${trIdx}`" v-model:model-value="tr.bloodType" placeholder="如：A型Rh阳性" />
            </div>
            <div class="form-group">
              <label :for="`transfusion-reaction-${trIdx}`">输血不良反应</label>
              <textarea 
                :id="`transfusion-reaction-${trIdx}`" 
                class="form-input"
                rows="2" 
                :value="tr.reaction"
                @input="(e: any) => handleTextareaInput(`transfusions.reaction-${trIdx}`, e)"
                placeholder="如无，请填'无'"
              ></textarea>
            </div>
          </div>
        </div>
          <nut-button block type="primary" @click="addTransfusion">添加输血记录</nut-button>

        <div class="no-history">
          <div class="checkbox-item" :class="{ 'is-checked': form.noTransfusionHistory }" @click="form.noTransfusionHistory = !form.noTransfusionHistory; onNoTransfusionChange()">
            <input type="checkbox" :checked="form.noTransfusionHistory" @change.stop /> 无输血史
          </div>
        </div>
      </div>

      <!-- 4. 过敏史 -->
      <div class="section">
        <div class="section-title">
          <span class="section-number">4</span>
          <span>过敏史</span>
        </div>

        <div class="allergy-highlight">【必须醒目标注，电子病历中常以红色或加粗字体提示】</div>

        <div id="allergy-container">
          <div class="allergy-item" v-for="(al, alIdx) in form.allergies" :key="al.id">
            <button v-if="form.allergies.length > 1" type="button" class="remove-btn" @click="removeAllergy(alIdx)">删除</button>
            <div class="form-group">
              <label :for="`allergen-type-${alIdx}`">过敏原类型</label>
              <select :id="`allergen-type-${alIdx}`" v-model="al.type">
                <option value="">请选择</option>
                <option value="药品">药品</option>
                <option value="食物">食物</option>
                <option value="其他">其他</option>
              </select>
            </div>
            <div class="form-group">
              <label :for="`allergen-detail-${alIdx}`">具体过敏原</label>
              <input :id="`allergen-detail-${alIdx}`" type="text" v-model="al.detail" placeholder="如：青霉素、海鲜、花粉、造影剂" />
            </div>
            <div class="form-group">
              <label :for="`allergy-reaction-${alIdx}`">过敏反应</label>
              <textarea 
                :id="`allergy-reaction-${alIdx}`" 
                class="form-input"
                rows="2" 
                :value="al.reaction"
                @input="(e: any) => handleTextareaInput(`allergies.reaction-${alIdx}`, e)"
                placeholder="具体症状，如：皮疹、呼吸困难"
              ></textarea>
            </div>
          </div>
        </div>
          <nut-button block type="primary" @click="addAllergy">添加过敏记录</nut-button>

        <div class="no-history">
          <div class="checkbox-item" :class="{ 'is-checked': form.noAllergyHistory }" @click="form.noAllergyHistory = !form.noAllergyHistory; onNoAllergyChange()">
            <input type="checkbox" :checked="form.noAllergyHistory" @change.stop /> 无过敏史
          </div>
        </div>
      </div>

      <div class="form-group">
        <div class="checkbox-item" :class="{ 'is-checked': form.confirmed }" @click="form.confirmed = !form.confirmed">
          <input type="checkbox" :checked="form.confirmed" @change.stop />
          确认信息无误，提交记录
        </div>
      </div>

      <nut-button block type="primary" :disabled="!form.confirmed" @click="onSubmit">提交记录</nut-button>
    </form>
  </div>

  <!-- 日期选择通用弹窗 -->
  <nut-calendar
    v-model:visible="surgeryCalendar.visible"
    type="one"
    title="选择日期"
    :default-value="surgeryCalendar.value || getTodayString()"
    @choose="onCommonDateChoose"
  />
  </CollapsibleSection>
</template>

<script setup lang="ts">
import CollapsibleSection from '@/components/CollapsibleSection.vue'
import { reactive, ref, nextTick, onMounted } from 'vue'
import Taro from '@tarojs/taro'

// 存储键名
const STORAGE_KEY = 'pastHistoryFormData'

interface Props {
  isExpanded: boolean
}

interface Emits {
  (e: 'toggle'): void
}

defineProps<Props>()
defineEmits<Emits>()

type Surgery = { id: number; name: string; date: string; reason: string; hospital: string; complications: string }
type Trauma = { id: number; type: string; date: string; treatment: string; sequelae: string }
type Transfusion = { id: number; reason: string; date: string; bloodType: string; reaction: string }
type Allergy = { id: number; type: string; detail: string; reaction: string }

const form = reactive({
  chronic: {
    cardiovascular: { items: [] as string[], other: '', details: '' },
    endocrine: { items: [] as string[], other: '', details: '' },
    respiratory: { items: [] as string[], other: '', details: '' },
    digestive: { items: [] as string[], other: '', details: '' },
    otherSystems: { items: [] as string[], other: '', details: '' }
  },
  noChronicDisease: false,
  surgeries: [ { id: 1, name: '', date: '', reason: '', hospital: '', complications: '' } as Surgery ],
  noSurgicalHistory: false,
  traumas: [ { id: 1, type: '', date: '', treatment: '', sequelae: '' } as Trauma ],
  transfusions: [ { id: 1, reason: '', date: '', bloodType: '', reaction: '' } as Transfusion ],
  noTransfusionHistory: false,
  allergies: [ { id: 1, type: '', detail: '', reaction: '' } as Allergy ],
  noAllergyHistory: false,
  confirmed: false
})

// 独立日期展示变量，避免深层数组响应问题
const surgeryDates = reactive<string[]>([])
const traumaDates = reactive<string[]>([])
const transfusionDates = reactive<string[]>([])
const refreshVersion = ref(0)

let surgeryIdCounter = 1
let traumaIdCounter = 1
let transfusionIdCounter = 1
let allergyIdCounter = 1

function onNoChronicChange() {
  if (form.noChronicDisease) {
    form.chronic.cardiovascular = { items: [], other: '', details: '' }
    form.chronic.endocrine = { items: [], other: '', details: '' }
    form.chronic.respiratory = { items: [], other: '', details: '' }
    form.chronic.digestive = { items: [], other: '', details: '' }
    form.chronic.otherSystems = { items: [], other: '', details: '' }
  }
}

function addSurgery() {
  surgeryIdCounter += 1
  const d = getTodayString()
  form.surgeries.push({ id: surgeryIdCounter, name: '', date: d, reason: '', hospital: '', complications: '' })
  surgeryDates.push(d)
}
function removeSurgery(index: number) {
  form.surgeries.splice(index, 1)
  surgeryDates.splice(index, 1)
  if (form.surgeries.length === 0) addSurgery()
}

function addTrauma() {
  traumaIdCounter += 1
  const d = getTodayString()
  form.traumas.push({ id: traumaIdCounter, type: '', date: d, treatment: '', sequelae: '' })
  traumaDates.push(d)
}
function removeTrauma(index: number) {
  form.traumas.splice(index, 1)
  traumaDates.splice(index, 1)
  if (form.traumas.length === 0) addTrauma()
}

function addTransfusion() {
  transfusionIdCounter += 1
  const d = getTodayString()
  form.transfusions.push({ id: transfusionIdCounter, reason: '', date: d, bloodType: '', reaction: '' })
  transfusionDates.push(d)
}
function removeTransfusion(index: number) {
  form.transfusions.splice(index, 1)
  transfusionDates.splice(index, 1)
  if (form.transfusions.length === 0) addTransfusion()
}

function addAllergy() {
  allergyIdCounter += 1
  form.allergies.push({ id: allergyIdCounter, type: '', detail: '', reaction: '' })
}
function removeAllergy(index: number) {
  form.allergies.splice(index, 1)
  if (form.allergies.length === 0) addAllergy()
}

function onNoSurgicalChange() {
  if (form.noSurgicalHistory) {
    form.surgeries = [ { id: surgeryIdCounter + 1, name: '', date: '', reason: '', hospital: '', complications: '' } ]
    form.traumas = [ { id: traumaIdCounter + 1, type: '', date: '', treatment: '', sequelae: '' } ]
    surgeryIdCounter += 1
    traumaIdCounter += 1
  }
}

function onNoTransfusionChange() {
  if (form.noTransfusionHistory) {
    form.transfusions = [ { id: transfusionIdCounter + 1, reason: '', date: '', bloodType: '', reaction: '' } ]
    transfusionIdCounter += 1
  }
}

function onNoAllergyChange() {
  if (form.noAllergyHistory) {
    form.allergies = [ { id: allergyIdCounter + 1, type: '', detail: '', reaction: '' } ]
    allergyIdCounter += 1
  }
}

// 处理复选框点击（用于数组类型的复选框）
function toggleCheckbox(array: string[], value: string) {
  const index = array.indexOf(value)
  if (index > -1) {
    array.splice(index, 1)
  } else {
    array.push(value)
  }
}

// 处理 textarea 输入事件（兼容 Taro 和 Web 环境）
function handleTextareaInput(field: string, e: any) {
  const value = e?.detail?.value ?? e?.target?.value ?? e?.detail ?? ''
  console.log(`📝 textarea [${field}] 输入事件:`, { value })
  
  // 根据字段路径更新数据
  const fieldParts = field.split('.')
  if (fieldParts.length === 3) {
    const [obj, subObj, key] = fieldParts
    if (obj === 'chronic') {
      if (subObj === 'cardiovascular' && key === 'details') form.chronic.cardiovascular.details = value
      else if (subObj === 'endocrine' && key === 'details') form.chronic.endocrine.details = value
      else if (subObj === 'respiratory' && key === 'details') form.chronic.respiratory.details = value
      else if (subObj === 'digestive' && key === 'details') form.chronic.digestive.details = value
      else if (subObj === 'otherSystems' && key === 'details') form.chronic.otherSystems.details = value
    }
  } else if (fieldParts.length === 2) {
    const [obj, key] = fieldParts
    if (obj === 'surgeries' && key.startsWith('complications-')) {
      const idx = parseInt(key.split('-')[1])
      if (form.surgeries[idx]) form.surgeries[idx].complications = value
    } else if (obj === 'transfusions' && key.startsWith('reaction-')) {
      const idx = parseInt(key.split('-')[1])
      if (form.transfusions[idx]) form.transfusions[idx].reaction = value
    } else if (obj === 'allergies' && key.startsWith('reaction-')) {
      const idx = parseInt(key.split('-')[1])
      if (form.allergies[idx]) form.allergies[idx].reaction = value
    }
  }
  
  console.log(`✅ textarea [${field}] 已更新为:`, value)
}

// 深拷贝函数
function deepClone<T>(obj: T): T {
  return JSON.parse(JSON.stringify(obj))
}

// 保存表单数据到缓存
function saveFormData() {
  try {
    const formDataCopy = deepClone(form)
    Taro.setStorageSync(STORAGE_KEY, formDataCopy)
    console.log('✅ 既往史表单数据已保存到缓存')
  } catch (error: any) {
    console.error('❌ 保存表单数据失败:', error)
    Taro.showToast({
      title: '保存数据失败',
      icon: 'none',
      duration: 2000
    })
  }
}

// 从缓存读取表单数据
function loadFormData() {
  try {
    const savedData = Taro.getStorageSync(STORAGE_KEY)
    if (savedData) {
      const parsedData = typeof savedData === 'string' ? JSON.parse(savedData) : savedData
      if (parsedData && typeof parsedData === 'object') {
        // 深度合并数据
        if (parsedData.chronic) Object.assign(form.chronic, parsedData.chronic)
        if (parsedData.noChronicDisease !== undefined) form.noChronicDisease = parsedData.noChronicDisease
        if (parsedData.surgeries && Array.isArray(parsedData.surgeries)) form.surgeries = parsedData.surgeries
        if (parsedData.noSurgicalHistory !== undefined) form.noSurgicalHistory = parsedData.noSurgicalHistory
        if (parsedData.traumas && Array.isArray(parsedData.traumas)) form.traumas = parsedData.traumas
        if (parsedData.transfusions && Array.isArray(parsedData.transfusions)) form.transfusions = parsedData.transfusions
        if (parsedData.noTransfusionHistory !== undefined) form.noTransfusionHistory = parsedData.noTransfusionHistory
        if (parsedData.allergies && Array.isArray(parsedData.allergies)) form.allergies = parsedData.allergies
        if (parsedData.noAllergyHistory !== undefined) form.noAllergyHistory = parsedData.noAllergyHistory
        if (parsedData.confirmed !== undefined) form.confirmed = parsedData.confirmed
        
        // 恢复日期显示
        if (parsedData.surgeries) {
          parsedData.surgeries.forEach((s: any, idx: number) => {
            if (s.date) surgeryDates[idx] = s.date
          })
        }
        if (parsedData.traumas) {
          parsedData.traumas.forEach((t: any, idx: number) => {
            if (t.date) traumaDates[idx] = t.date
          })
        }
        if (parsedData.transfusions) {
          parsedData.transfusions.forEach((tr: any, idx: number) => {
            if (tr.date) transfusionDates[idx] = tr.date
          })
        }
        
        console.log('✅ 既往史表单数据已从缓存加载')
      }
    }
  } catch (error: any) {
    console.error('❌ 加载表单数据失败:', error)
  }
}

// 组件挂载时加载缓存数据
onMounted(() => {
  loadFormData()
})

function onSubmit() {
  // 保存数据到缓存
  saveFormData()
  
  // 这里可替换为真实提交逻辑
  Taro.showToast({
    title: '既往史记录提交成功！',
    icon: 'success',
    duration: 2000
  })
}

// 通用日期弹窗（用于手术/外伤/输血日期）
const surgeryCalendar = reactive({ visible: false, group: '' as 'surgery'|'trauma'|'transfusion'|'', index: -1 as number, value: '' as any })

function openSurgeryCalendar(index: number) {
  openCommonCalendar('surgery', index)
}

// 获取当前日期字符串（格式：YYYY-MM-DD）
function getTodayString(): string {
  const today = new Date()
  const year = today.getFullYear()
  const month = String(today.getMonth() + 1).padStart(2, '0')
  const day = String(today.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

function openCommonCalendar(group: 'surgery'|'trauma'|'transfusion', index: number) {
  surgeryCalendar.group = group
  surgeryCalendar.index = index
  const todayStr = getTodayString()
  if (group === 'surgery') {
    surgeryCalendar.value = form.surgeries[index]?.date || todayStr
  }
  if (group === 'trauma') {
    surgeryCalendar.value = form.traumas[index]?.date || todayStr
  }
  if (group === 'transfusion') {
    surgeryCalendar.value = form.transfusions[index]?.date || todayStr
  }
  // 调试信息
  console.log('[Calendar] open', { group, index, defaultValue: surgeryCalendar.value })
  surgeryCalendar.visible = true
}

function toDateString(val: any): string {
  if (!val) return ''
  if (typeof val === 'string') return val
  if (Array.isArray(val)) {
    if (typeof val[0] === 'string' && /\d{4}-\d{2}-\d{2}/.test(val[0])) return val[0]
    if (val.length >= 3) return `${val[0]}-${`${val[1]}`.padStart(2,'0')}-${`${val[2]}`.padStart(2,'0')}`
    return val[0] || ''
  }
  if (val.selectedValue && Array.isArray(val.selectedValue)) {
    const sv = val.selectedValue
    if (typeof sv[0] === 'string' && /\d{4}-\d{2}-\d{2}/.test(sv[0])) return sv[0]
    if (sv.length >= 3) return `${sv[0]}-${`${sv[1]}`.padStart(2,'0')}-${`${sv[2]}`.padStart(2,'0')}`
    return sv[0] || ''
  }
  if (val.startDate) return val.startDate
  if (val.date) return val.date
  if (val instanceof Date) {
    const y = val.getFullYear()
    const m = `${val.getMonth() + 1}`.padStart(2, '0')
    const d = `${val.getDate()}`.padStart(2, '0')
    return `${y}-${m}-${d}`
  }
  return ''
}

function onCalendarSelect(val: any) {
  const ds = toDateString(val)
  console.log('[Calendar] select', val, '=>', ds)
  surgeryCalendar.value = ds
}

function onCommonDateChoose(val: any) {
  let ds = toDateString(val)
  if (!ds) ds = toDateString(surgeryCalendar.value)
  if (!ds) ds = getTodayString()
  if (surgeryCalendar.index >= 0) {
    if (surgeryCalendar.group === 'surgery') {
      const cur = form.surgeries[surgeryCalendar.index]
      form.surgeries.splice(surgeryCalendar.index, 1, { ...cur, date: ds })
      surgeryDates[surgeryCalendar.index] = ds
    } else if (surgeryCalendar.group === 'trauma') {
      const cur = form.traumas[surgeryCalendar.index]
      form.traumas.splice(surgeryCalendar.index, 1, { ...cur, date: ds })
      traumaDates[surgeryCalendar.index] = ds
    } else if (surgeryCalendar.group === 'transfusion') {
      const cur = form.transfusions[surgeryCalendar.index]
      form.transfusions.splice(surgeryCalendar.index, 1, { ...cur, date: ds })
      transfusionDates[surgeryCalendar.index] = ds
    }
  }
  refreshVersion.value += 1
  surgeryCalendar.visible = false
}

function onSurgeryPickerChange(e: any, idx: number) {
  const v = e?.detail?.value ?? e?.target?.value ?? ''
  if (v && form.surgeries[idx]) {
    const cur = form.surgeries[idx]
    form.surgeries.splice(idx, 1, { ...cur, date: v })
  }
}

function onTraumaPickerChange(e: any, idx: number) {
  const v = e?.detail?.value ?? e?.target?.value ?? ''
  if (v && form.traumas[idx]) {
    const cur = form.traumas[idx]
    form.traumas.splice(idx, 1, { ...cur, date: v })
  }
}

function onTransfusionPickerChange(e: any, idx: number) {
  const v = e?.detail?.value ?? e?.target?.value ?? ''
  if (v && form.transfusions[idx]) {
    const cur = form.transfusions[idx]
    form.transfusions.splice(idx, 1, { ...cur, date: v })
  }
}
</script>


<style scoped>
.form-container {
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
  padding: 24rpx;
}
.tip {
  text-align: center;
  margin-bottom: 24rpx;
  color: #666;
  font-size: 26rpx;
  line-height: 1.6;
}
.section {
  margin-bottom: 28rpx;
  padding-bottom: 24rpx;
  border-bottom: 1px dashed #eee;
}
.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  font-weight: 600;
  font-size: 30rpx;
  color: #333;
}
.section-number {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 44rpx;
  height: 44rpx;
  background-color: #2c80ff;
  color: #fff;
  border-radius: 50%;
  margin-right: 12rpx;
  font-size: 24rpx;
  font-weight: 600;
}
.subsection { margin-left: 20rpx; margin-bottom: 24rpx; }
.subsection-title { font-weight: 600; margin-bottom: 16rpx; color: #555; font-size: 28rpx; }
.form-group { margin-bottom: 24rpx; }
label { display: block; margin-bottom: 12rpx; font-weight: 600; font-size: 28rpx; color: #333; line-height: 1.5; }

/* 所有输入框统一样式 - 优化字体、背景和边框 */
.form-input,
input[type='text'],
input[type='number'],
input[type='date'],
select,
textarea {
  width: 100%;
  padding: 24rpx 24rpx;
  border: 2rpx solid #d0d7de;
  border-radius: 12rpx;
  font-size: 28rpx !important;
  background-color: #f8f9fa !important;
  color: #333 !important;
  box-sizing: border-box;
  -webkit-appearance: none;
  appearance: none;
  line-height: 1.6;
  min-height: 72rpx;
  transition: all 0.3s ease;
  font-weight: 500;
  display: block;
}

.form-input:hover,
input[type='text']:hover,
input[type='number']:hover,
input[type='date']:hover,
select:hover,
textarea:hover {
  border-color: #b0b7c0 !important;
  background-color: #f0f1f3 !important;
}

.form-input:focus,
input:focus,
input[type='text']:focus,
input[type='number']:focus,
input[type='date']:focus,
select:focus,
textarea:focus {
  border-color: #2c80ff !important;
  background-color: #fff !important;
  outline: none;
  box-shadow: 0 0 0 4rpx rgba(44, 128, 255, 0.15) !important;
  transform: translateY(-1rpx);
}

textarea.form-input,
textarea {
  min-height: 150rpx;
  resize: vertical;
  font-family: inherit;
  font-size: 28rpx !important;
  line-height: 1.6;
  padding: 24rpx 24rpx;
  background-color: #f8f9fa !important;
  border: 2rpx solid #d0d7de;
  border-radius: 12rpx;
  transition: all 0.3s ease;
  font-weight: 500;
}
.checkbox-group { display: flex; flex-direction: column; gap: 16rpx; margin-top: 12rpx; }
.checkbox-item { 
  display: flex; 
  align-items: center; 
  gap: 12rpx; 
  padding: 20rpx 16rpx; 
  background: #f9f9f9; 
  border-radius: 12rpx; 
  min-height: 64rpx;
  font-size: 28rpx;
  transition: all 0.2s ease;
  border: 2rpx solid #e9ecef;
  cursor: pointer;
  position: relative;
}

.checkbox-item:active { 
  background-color: #f0f0f0; 
}

/* 选中状态样式 */
.checkbox-item:has(input:checked),
.checkbox-item.is-checked {
  background-color: #e7f3ff !important;
  border-color: #2c80ff !important;
  border-width: 2rpx !important;
  box-shadow: 0 2rpx 8rpx rgba(44, 128, 255, 0.15);
}

.checkbox-item input[type="checkbox"] {
  width: 28rpx;
  height: 28rpx;
  min-width: 28rpx;
  min-height: 28rpx;
  cursor: pointer;
  accent-color: #2c80ff;
  flex-shrink: 0;
  margin: 0;
}

.checkbox-item input[type="checkbox"]:checked {
  accent-color: #2c80ff;
}

/* 选中时文字颜色和字重 */
.checkbox-item:has(input:checked),
.checkbox-item.is-checked {
  color: #2c80ff;
  font-weight: 600;
}

/* 确保选中时整个 checkbox-item 的文字都变色 */
.checkbox-item:has(input:checked) *,
.checkbox-item.is-checked * {
  color: #2c80ff;
  font-weight: 600;
}

/* 但保持 input 本身的样式 */
.checkbox-item:has(input:checked) input,
.checkbox-item.is-checked input {
  color: initial;
  font-weight: initial;
}

/* checkbox 标签样式 - 不换行 */
.checkbox-label {
  white-space: nowrap;
  flex-shrink: 0;
}

/* NutUI 组件样式统一 */
:deep(.nut-input) {
  font-size: 28rpx !important;
  background-color: #f8f9fa !important;
  border: 2rpx solid #d0d7de !important;
  border-radius: 12rpx !important;
  min-height: 72rpx !important;
  padding: 24rpx 24rpx !important;
}

:deep(.nut-input:focus) {
  border-color: #2c80ff !important;
  background-color: #fff !important;
  box-shadow: 0 0 0 4rpx rgba(44, 128, 255, 0.15) !important;
}

:deep(.nut-button) {
  font-size: 28rpx !important;
  min-height: 72rpx !important;
  font-weight: 600 !important;
  border-radius: 12rpx !important;
}

.inline-input { 
  display: block; 
  width: 100%; 
  margin-top: 12rpx; 
  margin-left: 0; 
  padding: 16rpx 20rpx; 
  font-size: 28rpx !important; 
  border: 2rpx solid #d0d7de;
  border-radius: 12rpx;
  background-color: #f8f9fa !important;
}
.date-display { 
  width: 100%; 
  padding: 24rpx 24rpx; 
  border: 2rpx solid #d0d7de; 
  border-radius: 12rpx; 
  min-height: 72rpx; 
  font-size: 28rpx !important; 
  display: flex; 
  align-items: center; 
  color: #333; 
  background: #f8f9fa !important;
  cursor: pointer;
  transition: all 0.3s ease;
}
.date-display:active { background-color: #f0f1f3 !important; }
.date-display:empty::before { content: '请选择日期'; color: #999; }
.details-section { margin-top: 12rpx; padding-top: 12rpx; border-top: 1px dashed #eee; }
.disease-item, .surgery-item, .allergy-item { 
  background-color: #f9f9f9; 
  padding: 24rpx; 
  border-radius: 12rpx; 
  margin-bottom: 24rpx;
  border: 2rpx solid #e9ecef;
}
.add-btn { 
  background-color: #2c80ff; 
  color: #fff; 
  border: none; 
  border-radius: 12rpx; 
  padding: 16rpx 24rpx; 
  font-size: 28rpx; 
  cursor: pointer; 
  margin-top: 16rpx; 
  width: 100%; 
  min-height: 72rpx; 
  font-weight: 600;
  transition: all 0.2s ease;
  box-shadow: 0 2rpx 8rpx rgba(44, 128, 255, 0.2);
}
.add-btn:active { background-color: #1a6fe0; }
.remove-btn { 
  background-color: #ff4757; 
  color: #fff; 
  border: none; 
  border-radius: 12rpx; 
  padding: 12rpx 18rpx; 
  font-size: 26rpx; 
  cursor: pointer; 
  margin-bottom: 16rpx; 
  width: 100%; 
  min-height: 64rpx; 
  font-weight: 600;
  transition: all 0.2s ease;
  box-shadow: 0 2rpx 8rpx rgba(255, 71, 87, 0.2);
}
.remove-btn:active { background-color: #e63946; }
.allergy-highlight { 
  color: #ff4757; 
  font-weight: 700; 
  border-left: 4rpx solid #ff4757; 
  padding-left: 16rpx; 
  margin: 16rpx 0;
  font-size: 26rpx;
}
.no-history { color: #888; font-style: italic; margin: 16rpx 0; font-size: 26rpx; }
.submit-btn { 
  background-color: #2c80ff; 
  color: #fff; 
  border: none; 
  border-radius: 12rpx; 
  padding: 16rpx 24rpx; 
  font-size: 28rpx; 
  cursor: pointer; 
  width: 100%; 
  min-height: 72rpx; 
  margin-top: 24rpx;
  font-weight: 600;
  transition: all 0.2s ease;
  box-shadow: 0 4rpx 12rpx rgba(44, 128, 255, 0.3);
}
.submit-btn:active:not(:disabled) { background-color: #1a6fe0; }
.submit-btn:disabled { opacity: 0.6; cursor: not-allowed; }
</style>
